package com.dreamer.view.pyramid;

import com.dreamer.domain.lottery.Prize;
import com.dreamer.domain.pyramid.Pyramid;
import com.dreamer.domain.user.User;
import com.dreamer.service.pyramid.PyramidHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import ps.mx.otter.utils.SearchParameter;
import ps.mx.otter.utils.WebUtil;
import ps.mx.otter.utils.message.Message;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/pyramid")
public class PyramidQueryController {

    @Autowired
    private PyramidHandler pyramidHandler;

    @RequestMapping("/index.html")
    public String index(
            @ModelAttribute("parameter") SearchParameter<Pyramid> parameter,
            HttpServletRequest request, Model model) {
        try {
            List<Pyramid> list = pyramidHandler.searchAllByPage(parameter);
            WebUtil.turnPage(parameter, request);
            model.addAttribute("PyramidList", list);
        } catch (Exception exp) {
            exp.printStackTrace();
        }
        return "pyramid/pyramid_index1";
    }

    @RequestMapping(value = "/edit.html", method = RequestMethod.GET)
    public String edit_enter(@ModelAttribute("parameter") SearchParameter<Pyramid> parameter, HttpServletRequest request,Model model) {
        User user = (User) WebUtil.getCurrentUser(request);
        if (user.isAdmin()) {
            return "pyramid/pyramid_edit";
        } else {
            return "common/403";
        }
    }

    @ModelAttribute("parameter")
    public SearchParameter<Pyramid> preprocess(@RequestParam("id") Optional<Integer> id) {
        SearchParameter<Pyramid> parameter = new SearchParameter<>();
        Pyramid  pyramid;
        if (id.isPresent()) {
            pyramid = pyramidHandler.findById(id.get());
        }else {
            pyramid=new Pyramid();
        }
        parameter.setEntity(pyramid);
        return parameter;
    }

    @ResponseBody
    @RequestMapping(value = "/encrypt.json", method = RequestMethod.POST)
    public Message encrypt(String encryptLotteryCode) {
        byte[] b = null;
        String s = null;
        try {
            b = encryptLotteryCode.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return Message.createSuccessMessage("success",s);
    }

}
